  package scoreCard.LivestockJudging3C;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import scoreCard.LivestockJudging3C.R;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class HistoryActivity extends ListActivity{
	private File currentDir;
    private FileArrayAdapter adapter;
    static final int CUSTOM_DIALOG = 1;
    private Option selectedOption = null;
    TextView customDialog_TextView;
    EditText customDialog_EditText;
    EditText customDialog_EditText2;
    EditText questcustomDialog_EditText;
    Button customDialog_Update, customDialog_Dismiss;
    EditText addtionalDialog_EditText;
    static final int SCORE_DIALOG = 2;
    static final int ADDL_SCORE_DIALOG = 3;
    private static final int RECORDING_DIALOG = 4;
    private static final int DELETE_ALL_DIALOG = 5;
    private static final int QUESTION_SCORE_DIALOG = 6;
    private static final int QUESTION_DELETE_DIALOG = 7;
    private static final int OTHER_DELETE_DIALOG = 8;
    
	 /** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.history);
        
        Bundle info = getIntent().getExtras();
        String compName = "";
        String className = "";
		if (info != null) {
			compName = info.getString("Competition");
			className = info.getString("Class");
		}
	    
		 // Fill Array
        String extStorageDirectory;
        if (className != null && className.length() > 0) {
        	extStorageDirectory = (Environment.getExternalStorageDirectory()+"/3C/Competition/" + compName +"/" + className).toString();
        } else {
        	extStorageDirectory = (Environment.getExternalStorageDirectory()+"/3C/Competition/" + compName).toString();
        }
        
        currentDir = new File(extStorageDirectory);
        fill(currentDir);
    }
    
	private void fill(File f)
    {
    	 File[]dirs = f.listFiles();
		 this.setTitle("Current: "+f.getName());
		 List<Option>dir = new ArrayList<Option>();
		 List<Option>fls = new ArrayList<Option>();
		 List<Option>ignore = new ArrayList<Option>();
		 
		 String extStorDir = (Environment.getExternalStorageDirectory()+"/3C/Competition").toString();
		 File k = new File(extStorDir);
		 String[] filedir = k.list();
		 try{
			 for(File ff: dirs)
			 {
				 // Competition Names
				 // Class Names
				 // Recordings
				if(ff.isDirectory()) {
					boolean jump = false;
					//Check Comp Names
					for (int c = 0; c < filedir.length; c++) {
						// Comp Name
						if (ff.getName().equals(filedir[c])) {
							dir.add(new Option(ff.getName(),"Competitions",ff.getAbsolutePath()));
							jump = true;
						}
					}
					if (!jump) {
						dir.add(new Option(ff.getName(),"Class",ff.getAbsolutePath()));
					}
				} else if (ff.isFile() && ff.getName().equalsIgnoreCase("scores.ser")){
					// Hide Scores map
					ignore.add(new Option(ff.getName(),"Scores.ser",ff.getAbsolutePath()));
				} else if (ff.isFile() && ff.getName().contains(".3gp")){
					// Recording file
					fls.add(new Option(ff.getName(),"Recording",ff.getAbsolutePath()));
				}
			 }
		 }catch(Exception e) {
			 // Need bug error
		 }
		 Collections.sort(dir);
		 Collections.sort(fls);
		 
		 dir.addAll(fls);
		 // Comp Folders
		 if(!f.getName().equalsIgnoreCase("Competition") && (f.getParent().equals(extStorDir))){
			 dir.add(0,new Option("..","Back to Competitions",f.getParent()));
			 // Total Score
			 try {
				 String path = f.getPath();
				 Map<String, Integer> scores = deserializeScores(path);
				 Iterator<Entry<String, Integer>> it = scores.entrySet().iterator();
				 int totalScore = 0;
				 while (it.hasNext()) {
					 Map.Entry pairs = (Map.Entry)it.next();
					 totalScore += Integer.parseInt(pairs.getValue().toString());
					 // Keep Cull and Additional display
					 if((pairs.getKey().toString()).contains("Keep") || (pairs.getKey().toString()).contains("Additional")) {
						 dir.add(new Option(pairs.getKey().toString(),pairs.getValue().toString(),f.getPath()));
					 }		
				 }
				 dir.add(new Option("Total Score",String.valueOf(totalScore),f.getPath()));
			 } catch (NumberFormatException e) {
				 e.printStackTrace();
			 }
			 dir.add(new Option("Add Keep/Cull","",f.getParent()));
			 dir.add(new Option("Add Additional Score","",f.getParent()));
			 dir.add(new Option("Add Placing Score","",f.getParent()));
			 dir.add(new Option("Add Recording","",f.getParent()));
		 } else if (!(f.getParent().equals(extStorDir)) && !f.getName().equalsIgnoreCase("Competition")) { // Class Folders
			 dir.add(0,new Option("..","Back to " + f.getParentFile().getName(),f.getParent()));
			String classscore = f.getParent();
			Map<String, Integer> cScores = deserializeScores(classscore);
			String className = f.getName();
			if (cScores.containsKey(className)) {
				int hold = cScores.get(className);
				dir.add(new Option("Placing Score","" + hold,f.getPath()));
				
			} 
			Iterator<Entry<String, Integer>> it = cScores.entrySet().iterator();
			 while (it.hasNext()) {
				 Map.Entry pairs = (Map.Entry)it.next();
				 if((pairs.getKey().toString()).contains("Q") && pairs.getKey().toString().contains(className)) {
					 dir.add(new Option("Question Score",pairs.getValue().toString(),f.getPath()));
				 }		
			 }
			 dir.add(new Option("Add Question Score","",f.getParent()));
		 }

		 adapter = new FileArrayAdapter(HistoryActivity.this,R.layout.file_view,dir); 
		 this.setListAdapter(adapter);
    }
	
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Option o = adapter.getItem(position);
		if(o.getData().equalsIgnoreCase("competitions")||o.getData().contains("Back to")||o.getData().equalsIgnoreCase("class")){
				currentDir = new File(o.getPath());
				fill(currentDir);
		} else {
			onFileClick(o);
		}
	}

    private void onFileClick(Option o)
    {
    	selectedOption = o;
    	if(o.getName().equals("Add Placing Score")){
    		Intent intent = new Intent(HistoryActivity.this,ScoreCalculatorActivity.class);
    		Bundle info  = new Bundle();
    		String selffillcomp = currentDir.getName();
    		info.putString("Parent",selffillcomp);
    		intent.putExtras(info);
    		startActivity(intent);
    	}
    	else if(o.getName().equals("Add Recording")) {
    		Intent intent = new Intent(HistoryActivity.this,VoiceRecorderActivity.class);
    		Bundle info  = new Bundle();
    		info.putString("Parent",currentDir.getName());
    		intent.putExtras(info);
    		startActivity(intent);
    	}
    	else if(o.getName().equals("Add Keep/Cull")) {
    		showDialog(CUSTOM_DIALOG);
    	}
    	else if(o.getName().equals("Add Additional Score")){
    		showDialog(ADDL_SCORE_DIALOG);
    	}
    	else if(o.getName().equals("Add Question Score")){
    		showDialog(QUESTION_SCORE_DIALOG);
    	}
    	else if(o.getName().equals("Placing Score")) {
    		showDialog(SCORE_DIALOG);
    	}
    	else if(o.getName().contains("Question")) {
    		showDialog(QUESTION_DELETE_DIALOG);
    	}
    	else if (o.getData().equals("Recording")) {
    		showDialog(RECORDING_DIALOG);
    	}
    	else if (o.getName().contains("Total Score")) {
    		showDialog(DELETE_ALL_DIALOG);
    	} else if (o.getName().contains("Keep/Cull") || o.getName().contains("Additional")) {
    		showDialog(OTHER_DELETE_DIALOG);
    	}
    }
    
    public Dialog onCreateDialog(int id) {
    	final Dialog dialog;
    	switch(id) {
	    	case(CUSTOM_DIALOG):{
	    		dialog = new Dialog(HistoryActivity.this);
	    		dialog.setContentView(R.layout.customdialog);
	    	    dialog.setTitle("Add Keep/Cull");
	    	    customDialog_EditText = (EditText)dialog.findViewById(R.id.dialogedittext);
	    	    customDialog_TextView = (TextView)dialog.findViewById(R.id.dialogtextview);
	    	    customDialog_EditText2 = (EditText)dialog.findViewById(R.id.dialogeditclass);
	    	    customDialog_Update = (Button)dialog.findViewById(R.id.dialogupdate);
	    	    customDialog_Dismiss = (Button)dialog.findViewById(R.id.dialogdismiss);	    	    
	    	    customDialog_Update.setOnClickListener(customDialog_UpdateOnClickListener);
	    	    customDialog_Dismiss.setOnClickListener(customDialog_DismissOnClickListener);
	    	    break;
	    	} 
	    	case(RECORDING_DIALOG):{
	    		dialog = new Dialog(HistoryActivity.this);
	    		dialog.setContentView(R.layout.recordingdialog);
	    	    dialog.setTitle("Play or delete?");
	    	    
	    	    Button playButton = (Button)dialog.findViewById(R.id.dialogPlayButton);
	    	    Button deleteButton = (Button)dialog.findViewById(R.id.dialogDeleteButton);
	    	    Button cancelButton = (Button)dialog.findViewById(R.id.dialogCancelButton);
	    	    playButton.setOnClickListener(new OnClickListener() {

					public void onClick(View view) {
						Intent intent = new Intent(HistoryActivity.this, VoiceRecorderActivity.class);
				    	Bundle info = new Bundle();
				    	info.putString("path", selectedOption.getPath());
				    	intent.putExtras(info);
						startActivity(intent);
					}
	    	    	
	    	    });
	    	    deleteButton.setOnClickListener(new OnClickListener() {

					public void onClick(View view) {
						File toDelete = new File(selectedOption.getPath());
						File parent = toDelete.getParentFile();
						toDelete.delete();
						dialog.dismiss();
						fill(parent);
					}
	    	    	
	    	    });
	    	    cancelButton.setOnClickListener(new OnClickListener() {

					public void onClick(View view) {
						dialog.dismiss();
					}
	    	    	
	    	    });
	    	    break;
	    	} 
	    	case(SCORE_DIALOG):{
	    		AlertDialog.Builder editscoreDialog = new AlertDialog.Builder(HistoryActivity.this);
	    		editscoreDialog.setMessage("Delete this score?");
	    		editscoreDialog.setPositiveButton("Delete",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// Find line in Scores.txt
								
								File className = new File(selectedOption.getPath());
								Map<String,Integer> scores = deserializeScores(className.getParent());
								String name = className.getName();
								scores.remove(name);
								serializeScores(scores, className.getParent());
								dialog.dismiss();
								fill(className);
							}
						});
	    		editscoreDialog.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
				return editscoreDialog.create();
	    	}
	    	case(OTHER_DELETE_DIALOG):{
	    		AlertDialog.Builder editscoreDialog = new AlertDialog.Builder(HistoryActivity.this);
	    		editscoreDialog.setMessage("Delete this score?");
	    		editscoreDialog.setPositiveButton("Delete",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								Map<String,Integer> scores = deserializeScores(selectedOption.getPath());
								scores.remove(selectedOption.getName());
								serializeScores(scores, selectedOption.getPath());
								dialog.dismiss();
								fill(new File(selectedOption.getPath()));
							}
						});
	    		editscoreDialog.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
				return editscoreDialog.create();
	    	}
	    	case(QUESTION_DELETE_DIALOG):{
	    		AlertDialog.Builder editscoreDialog = new AlertDialog.Builder(HistoryActivity.this);
	    		editscoreDialog.setMessage("Delete this score?");
	    		editscoreDialog.setPositiveButton("Delete",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// Find line in Scores.txt
								File className = new File(selectedOption.getPath());
								Map<String,Integer> scores = deserializeScores(className.getParent());
								String name = className.getName();
								scores.remove(name+'Q');
								serializeScores(scores, className.getParent());
								dialog.dismiss();
								fill(className);
							}
						});
	    		editscoreDialog.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
				return editscoreDialog.create();
	    	}
	    	case(DELETE_ALL_DIALOG):{
	    		AlertDialog.Builder deleteAllDialog = new AlertDialog.Builder(this);
	    		deleteAllDialog.setMessage("Delete all scores for this competition?");
	    		deleteAllDialog.setPositiveButton("Delete",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// Find line in Scores.txt
								
								serializeScores(new HashMap<String,Integer>(), selectedOption.getPath());
								dialog.dismiss();
								fill(new File(selectedOption.getPath()));
							}
						});
	    		deleteAllDialog.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.dismiss();
							}
						});
				return deleteAllDialog.create();
	    	}
	    	case(ADDL_SCORE_DIALOG):{
	    		dialog = new Dialog(HistoryActivity.this);
	    		dialog.setContentView(R.layout.addlscoredialog);
	    	    dialog.setTitle("Add Additional Score: ");
	    	    addtionalDialog_EditText = (EditText)dialog.findViewById(R.id.addldialogeditscore);
	    	    customDialog_TextView = (TextView)dialog.findViewById(R.id.addldialogtextview);
	    	    customDialog_Update = (Button)dialog.findViewById(R.id.addldialogupdate);
	    	    customDialog_Dismiss = (Button)dialog.findViewById(R.id.addldialogdismiss);	    	    
	    	    customDialog_Update.setOnClickListener(addlcustomDialog_UpdateOnClickListener);
	    	    customDialog_Dismiss.setOnClickListener(addlcustomDialog_DismissOnClickListener);
	    	    break;
	    	}
	    	case(QUESTION_SCORE_DIALOG): {
	    		dialog = new Dialog(HistoryActivity.this);
	    		dialog.setContentView(R.layout.questionscoredialog);
	    	    dialog.setTitle("Add Question Score: ");
	    	    questcustomDialog_EditText = (EditText)dialog.findViewById(R.id.questdialogeditscore);
	    	    customDialog_TextView = (TextView)dialog.findViewById(R.id.questdialogtextview);
	    	    customDialog_Update = (Button)dialog.findViewById(R.id.questdialogupdate);
	    	    customDialog_Dismiss = (Button)dialog.findViewById(R.id.questdialogdismiss);	    	    
	    	    customDialog_Update.setOnClickListener(questcustomDialog_UpdateOnClickListener);
	    	    customDialog_Dismiss.setOnClickListener(questcustomDialog_DismissOnClickListener);
	    		break;
	    	}
	    	default :
	    		dialog = null;
    	}
    	return dialog;
    }
    
    private Map<String, Integer> deserializeScores(String path) {
    	FileInputStream fis = null;
		ObjectInputStream in = null;
		try {
			fis = new FileInputStream(path + "/scores.ser");
			in = new ObjectInputStream(fis);
			Map<String, Integer> scores = (Map<String, Integer>) in.readObject();
			if (scores == null) {
				return new HashMap<String, Integer>();
			}
			return scores;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return new HashMap<String, Integer>();
		} catch (StreamCorruptedException e) {
			e.printStackTrace();
			return new HashMap<String, Integer>();
		} catch (IOException e) {
			e.printStackTrace();
			return new HashMap<String, Integer>();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return new HashMap<String, Integer>();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    }
    
    private boolean serializeScores(Map<String, Integer> scores, String path) {
		FileOutputStream fos = null;
		ObjectOutputStream out = null;
		try {
			if (scores == null) {
				scores = new HashMap<String, Integer>();
			}
			fos = new FileOutputStream(path + "/scores.ser");
			out = new ObjectOutputStream(fos);
			out.writeObject(scores);
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (StreamCorruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
    }
    
    private Button.OnClickListener addlcustomDialog_UpdateOnClickListener
    = new Button.OnClickListener(){
    	public void onClick(View arg0) {
    		if(addtionalDialog_EditText.getText().toString() != null && addtionalDialog_EditText.getText().toString() != "" ){
	    		try {
	    			int addlscore = Integer.parseInt(addtionalDialog_EditText.getText().toString());
		    		SaveFile save = new SaveFile();
		    		save.SaveScore(currentDir.getName(), "Additional Score", addlscore, false, false);
		    		dismissDialog(ADDL_SCORE_DIALOG);	
	    			fill(currentDir);
	    		} catch (NumberFormatException ex) {
	    			ex.printStackTrace();
	    		}
    		}
    		
    	}
    };
    
    private Button.OnClickListener questcustomDialog_UpdateOnClickListener
    = new Button.OnClickListener(){
    	public void onClick(View arg0) {    		
    		if(questcustomDialog_EditText.getText().toString() != null && questcustomDialog_EditText.getText().toString() != "" ){
	    		try {
	    			int addlscore = Integer.parseInt(questcustomDialog_EditText.getText().toString());
		    		SaveFile save = new SaveFile();
		    		save.SaveScore(currentDir.getParentFile().getName(),currentDir.getName(), addlscore, true, true);
		    		dismissDialog(QUESTION_SCORE_DIALOG);	
	    			fill(currentDir);
	    		} catch (NumberFormatException ex) {
	    			ex.printStackTrace();
	    		}
    		}
    		
    	}
    };
    private Button.OnClickListener customDialog_UpdateOnClickListener
    = new Button.OnClickListener(){
    	public void onClick(View arg0) {
    		if(customDialog_EditText.getText().toString() != null && customDialog_EditText.getText().toString() != "" ){
	    		try {
	    			int keepcullnumber = Integer.parseInt(customDialog_EditText.getText().toString());
		    		SaveFile save = new SaveFile();
		    		String keepcullclass = customDialog_EditText2.getText().toString();
		    		save.SaveScore(currentDir.getName(), keepcullclass + " " + "Keep/Cull", keepcullnumber, false, false);
		    		dismissDialog(CUSTOM_DIALOG);	
		    		fill(currentDir);
	    		} catch (NumberFormatException ex) {
	    			ex.printStackTrace();
	    		}
    		}
    		
    	}
    };
    private Button.OnClickListener addlcustomDialog_DismissOnClickListener
    = new Button.OnClickListener(){
	  public void onClick(View arg0) {
	   dismissDialog(ADDL_SCORE_DIALOG);
	  }
    };
    
    private Button.OnClickListener customDialog_DismissOnClickListener
    = new Button.OnClickListener(){
	  public void onClick(View arg0) {
	   dismissDialog(CUSTOM_DIALOG);
	  }
    };
    
    private Button.OnClickListener questcustomDialog_DismissOnClickListener
    = new Button.OnClickListener(){
	  public void onClick(View arg0) {
	   dismissDialog(QUESTION_SCORE_DIALOG);
	  }
    };
}
